#!/usr/bin/python -S
"""
pgi_sleep.py
"""

__author__ = 'Andy Chu'


import os
import sys
import time

import tnet


class Error(Exception):
  pass


def log(msg, *args):
  if args:
    msg = msg % args
  # TODO: Sometimes when running through xmap.py, I get this -- EWOULDBLOCK.
  # Why?  Oh because in xmap.py, I capture stderr and set it to nonblocking.
  # Why doesn't that happen with stdout?  I don't have much output here, but
  # maybe it's because stderr is unbuffered?
  # File "./sleep_.py", line 25, in log
  #  print >>sys.stderr, msg
  # IOError: [Errno 11] Resource temporarily unavailable
  print >>sys.stderr, msg


def main(argv):
  """Returns an exit code."""
  pid = os.getpid()
  log('Hello from pgi_sleep.py, pid %d', pid)

  while True:
    try:
      seconds = tnet.load(sys.stdin)
    except EOFError:
      break
    log('Sleeping %d', seconds)
    time.sleep(seconds)
    response = {'pid': pid, 'seconds': seconds}
    sys.stdout.write(tnet.dumps(response))

    # This is needed -- otherwise we would get 4K of responses at once...
    sys.stdout.flush()

  return 0


if __name__ == '__main__':
  try:
    sys.exit(main(sys.argv))
  except Error, e:
    print >> sys.stderr, e.args[0]
    sys.exit(1)
